class RunningController < ApplicationController
  include ActionView::Helpers::NumberHelper
  def is_game_open
    game = Game.find(session[:player].game_id)
    if session[:player].player_type=="B"
      if game.run_flag=='N'
        return true
      else
        word = 'คุณไม่สามารถดำเนินการระหว่างรอบการซื้อขายได้!!'
        redirect_to :controller=>"user", :action=>"plan_game", :word=>word
        return false
      end
    else
      if game.a_run_flag=='N'
        return true
      else
        word = 'คุณไม่สามารถดำเนินการระหว่างรอบการซื้อขายได้!!'
        redirect_to :controller=>"user", :action=>"plan_game_a", :word=>word
        return false
      end
    end
  end

  before_filter :is_game_open, :except=>[:close_futures, :close_futures2]
  def close_futures
    contract = Contract.find(params[:id])
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    settlement_price = nil
    word = ''
    if game.run_flag=='Y' && game_setting.last_price==nil
      word = 'กรุณารอราคาตลาด'
    else
      if game.run_flag=='Y'
        if game_setting.last_price
          settlement_price = game_setting.last_price
        else
          if game.current_year==1
            settlement_price = game_setting.f01_price.to_f
          else
            settlement_price = game_setting.average_price
          end
        end
      else
        if game.current_year==1
          settlement_price = (game_setting.f01_price.to_f/(1.0 + game_setting.level1_debt_rate)).round(2)
        else
          settlement_price = game_setting.average_price
        end
      end
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
      last_value = contract.current_value
      sold_price = nil
      if game.run_flag=='N'
        sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year + 1))).round(2)
      else
        sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year))).round(2)
      end
      val = nil
      if contract.c_type=='sell'
        val = (contract.unit_price - sold_price) * contract.total_unit
      else
        val = (sold_price - contract.unit_price) * contract.total_unit
      end
      current_value = contract.current_value + val
      current_value = (current_value/10000.0).round * 10000
      pb.cash = pb.cash + current_value
      pb.futures = pb.futures - last_value
      pb.futures_revenue = pb.futures_revenue - (last_value - current_value)
      pb.save
      contract.settlement_price = settlement_price
      contract.close_year = game.current_year
      contract.open_flag = 'N'
      contract.current_value = current_value
      contract.save

      if game.run_flag=='Y'
        game_setting.total_q = game_setting.total_q + contract.total_unit
        game_setting.total_mul = game_setting.total_mul + (settlement_price * contract.total_unit)
        game_setting.average_price = (game_setting.total_mul.to_f / game_setting.total_q).round(2)
        game_setting.save
      end
      word = "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def close_futures2
    contract = Contract.find(params[:id])
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    settlement_price = nil
    word = ''
    if game.run_flag=='Y' && game_setting.last_price==nil
      word = 'กรุณารอราคาตลาด'
    else
      if game.run_flag=='Y'
        if game_setting.last_price
          settlement_price = game_setting.last_price
        else
          if game.current_year==1
            settlement_price = game_setting.f01_price.to_f
          else
            settlement_price = game_setting.average_price
          end
        end
      else
        if game.current_year==1
          settlement_price = (game_setting.f01_price.to_f/(1.0 + game_setting.level1_debt_rate)).round(2)
        else
          settlement_price = game_setting.average_price
        end
      end
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
      last_value = contract.current_value
      sold_price = nil
      if game.run_flag=='N'
        sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year + 1))).round(2)
      else
        sold_price = (settlement_price * ((1.0 + game_setting.level1_debt_rate) ** (contract.end_year - game.current_year))).round(2)
      end
      val = nil
      if contract.c_type=='sell'
        val = (contract.unit_price - sold_price) * contract.total_unit
      else
        val = (sold_price - contract.unit_price) * contract.total_unit
      end
      current_value = contract.current_value + val
      current_value = (current_value/10000.0).round * 10000
      pb.cash = pb.cash + current_value
      pb.futures = pb.futures - last_value
      pb.futures_revenue = pb.futures_revenue - (last_value - current_value)
      pb.save
      contract.settlement_price = settlement_price
      contract.close_year = game.current_year
      contract.open_flag = 'N'
      contract.current_value = current_value
      contract.save

      if game.run_flag=='Y'
        game_setting.total_q = game_setting.total_q + contract.total_unit
        game_setting.total_mul = game_setting.total_mul + (settlement_price * contract.total_unit)
        game_setting.average_price = (game_setting.total_mul.to_f / game_setting.total_q).round(2)
        game_setting.save
      end

      word = "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"foundgame", :word=>word
  end

  def bs_futures
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    f1 = 25.0
    if game.current_year==1
      f1 = game_setting.f01_price
    else
      f1 = game_setting.average_price * (1 + game_setting.level1_debt_rate)
    end
    f2 = f1 * (1 + game_setting.level1_debt_rate)
    f3 = f2 * (1 + game_setting.level1_debt_rate)
    f1 = f1.round(2)
    f2 = f2.round(2)
    f3 = f3.round(2)
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    t = "buy"
    y = 1
    initial_cash = game_setting.initial_margin
    maintenance_cash = game_setting.maintenance_margin
    unit_price = f1
    total_unit = game_setting.contract_size
    if params[:b_y1]
      t = "buy"
      y = 1
      unit_price = f1
    end
    if params[:b_y2]
      t = "buy"
      y = 2
      unit_price = f2
    end
    if params[:b_y3]
      t = "buy"
      y = 3
      unit_price = f3
    end
    if params[:s_y1]
      t = "sell"
      y = 1
      unit_price = f1
    end
    if params[:s_y2]
      t = "sell"
      y = 2
      unit_price = f2
    end
    if params[:s_y3]
      t = "sell"
      y = 3
      unit_price = f3
    end
    limit = false
    total_buy = Contract.count(:conditions=>["player_id=? AND open_flag=? AND c_type=?", session[:player].id, 'Y', 'buy'])
    total_sell = Contract.count(:conditions=>["player_id=? AND open_flag=? AND c_type=?", session[:player].id, 'Y', 'sell'])
    position_limit = game_setting.position_limit
    if t=="buy"
      total_buy = total_buy+1
    else
      total_sell = total_sell+1
    end
    if (total_buy - total_sell).abs > position_limit
      limit = true
    end
    if pb.cash<initial_cash
      word = "เงินสดไม่เพียงพอ"
    elsif limit
      word = "เกิน Position Limit"
    else
      pb.cash = pb.cash - initial_cash
      pb.futures = pb.futures + initial_cash
      pb.save

      c = Contract.new
      c.game_id = game.id
      c.player_id = session[:player].id
      c.name = "FY#{game.current_year + y - 1}"
      c.start_year = game.current_year
      c.end_year = game.current_year + y - 1
      c.duration = y
      c.c_type = t
      c.unit_price = unit_price
      c.total_unit = total_unit
      c.total_value = (unit_price * total_unit).to_i
      c.initial_margin = initial_cash
      c.current_value = initial_cash
      c.maintenance_margin = maintenance_cash
      c.save
      word = "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def a_rawmat_order
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    unit_cost = game_setting.rawmat_unit_cost
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])

    total = ((number_with_precision(params[:rawmat_order], :precision=>2)).to_f * 1000000).to_i
    if pb.cash<(unit_cost*total)
      word = "เงินสดไม่เพียงพอ"
    elsif total<0
      word = "ไม่สามารถระบุค่าติดลบได้"
    else
      pb.rawmat_unit = pb.rawmat_unit + total
      pb.rawmat_cost = pb.rawmat_cost + (unit_cost*total)
      pb.rawmat_unitcost = pb.rawmat_cost.to_f/pb.rawmat_unit
      pb.cash = pb.cash - (unit_cost*total)
      if params[:rawandproduce]
        produce = pb.rawmat_unit
        factories = Factory.find(:all, :conditions=>["player_id=?", session[:player].id], :order=>"year")
        capacity = factories.size * game_setting.factory_capacity
        if produce>capacity
          produce = capacity
        end
        pb.onprocess_inventory_unit = produce
      end
      pb.save

      word = "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game_a", :word=>word
  end

  def a_rawmat_order_bk
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    unit_cost = game_setting.rawmat_unit_cost
    p = Player.find(session[:player].id)
    if p.level==0
    elsif p.level==1
      unit_cost = unit_cost - game_setting.level1_price_added
    elsif p.level==2
      unit_cost = unit_cost - game_setting.level2_price_added
    elsif p.level==3
      unit_cost = unit_cost - game_setting.level3_price_added
    else
      unit_cost = unit_cost - game_setting.level4_price_added
    end
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])

    total = ((number_with_precision(params[:rawmat_order], :precision=>2)).to_f * 1000000).to_i
    if pb.cash<(unit_cost*total)
      word = "เงินสดไม่เพียงพอ"
    elsif total<0
      word = "ไม่สามารถระบุค่าติดลบได้"
    else
      pb.rawmat_unit = pb.rawmat_unit + total
      pb.rawmat_cost = pb.rawmat_cost + (unit_cost*total)
      pb.rawmat_unitcost = pb.rawmat_cost.to_f/pb.rawmat_unit
      pb.cash = pb.cash - (unit_cost*total)
      if params[:rawandproduce]
        produce = pb.rawmat_unit
        factories = Factory.find(:all, :conditions=>["player_id=?", session[:player].id], :order=>"year")
        capacity = factories.size * game_setting.factory_capacity
        if produce>capacity
          produce = capacity
        end
        pb.onprocess_inventory_unit = produce
      end
      pb.save

      word = "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game_a", :word=>word
  end

  def b_rawmat_order
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    unit_cost = game_setting.unit_cost
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])

    total = ((number_with_precision(params[:rawmat_order], :precision=>2)).to_f * 1000000).to_i
    if pb.cash<(unit_cost*total)
      word = "เงินสดไม่เพียงพอ"
    elsif total<0
      word = "ไม่สามารถระบุค่าติดลบได้"
    else
      pb.rawmat_unit = pb.rawmat_unit + total
      pb.rawmat_cost = pb.rawmat_cost + (unit_cost*total)
      pb.rawmat_unitcost = pb.rawmat_cost.to_f/pb.rawmat_unit
      pb.cash = pb.cash - (unit_cost*total)
      if params[:rawandproduce]
        produce = pb.rawmat_unit
        factories = Factory.find(:all, :conditions=>["player_id=?", session[:player].id], :order=>"year")
        capacity = factories.size * game_setting.factory_capacity
        if produce>capacity
          produce = capacity
        end
        pb.onprocess_inventory_unit = produce
      end
      pb.save
      word = "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def buy_factory
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])

    if pb.cash<game_setting.factory_price
      word = "เงินสดไม่เพียงพอ"
    else
      max_code = 0
      last_f = Factory.find(:first, :conditions=>["player_id=?", session[:player].id], :order=>"id desc")
      if last_f
        max_code = last_f.code
      end
      f = Factory.new
      f.player_id = session[:player].id
      f.code = max_code + 1
      f.gencode = random_string(10)
      f.year = game.current_year
      f.price = game_setting.factory_price
      f.remain_value = game_setting.factory_price
      f.start_year = game.current_year
      f.end_year = game.current_year + game_setting.factory_life - 1
      f.save

      pb.cash = pb.cash - game_setting.factory_price
      pb.cap_ex = pb.cap_ex - game_setting.factory_price
      pb.save
      word = "Done! #{Time.now}"
    end

    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def buy_warehouse
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])

    if pb.cash<game_setting.warehouse_price
      word = "เงินสดไม่เพียงพอ"
    else
      max_code = 0
      last_w = Warehouse.find(:first, :conditions=>["player_id=?", session[:player].id], :order=>"id desc")
      if last_w
        max_code = last_w.code
      end
      w = Warehouse.new
      w.player_id = session[:player].id
      w.code = max_code + 1
      w.gencode = random_string(10)
      w.year = game.current_year
      w.price = game_setting.warehouse_price
      w.remain_value = game_setting.warehouse_price
      w.start_year = game.current_year
      w.end_year = game.current_year + game_setting.warehouse_life - 1
      w.save

      pb.cash = pb.cash - game_setting.warehouse_price
      pb.cap_ex = pb.cap_ex - game_setting.warehouse_price
      pb.save
      word = "Done! #{Time.now}"
    end

    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def sale_factory
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    f = Factory.find(:first, :conditions=>["gencode=?", params[:id]])
    market_price = (game_setting.factory_price * ((game_setting.factory_life - game.current_year + f.start_year)/game_setting.factory_life.to_f)).to_i

    if f
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
  #    pb.cash = pb.cash + f.remain_value
      pb.cash = pb.cash + market_price
      pb.cap_ex = pb.cap_ex + f.remain_value
      pb.etc = pb.etc + (market_price - f.remain_value)
      pb.etc_revenue = pb.etc_revenue + market_price
      pb.etc_cost = pb.etc_cost + f.remain_value
      pb.save

      f.destroy
    end

    remain_factory = Factory.count(:conditions=>["player_id=?", session[:player].id])
    capacity = remain_factory * game_setting.factory_capacity

    if capacity<pb.onprocess_inventory_unit
      word = 'ปรับแก้ปริมาณสั่งผลิตอัตโนมัติ, '
      #pb.cash = pb.cash + ((pb.onprocess_inventory_unit-capacity) * game_setting.unit_cost)
      pb.onprocess_inventory_unit = capacity
      pb.save
    end
    word += "Done! #{Time.now}"
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def sale_warehouse
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    w = Warehouse.find(:first, :conditions=>["gencode=?", params[:id]])
    market_price = (game_setting.warehouse_price * ((game_setting.warehouse_life - game.current_year + w.start_year)/game_setting.warehouse_life.to_f)).to_i
    if w
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
      #pb.cash = pb.cash + w.remain_value
      pb.cash = pb.cash + market_price
      pb.cap_ex = pb.cap_ex + w.remain_value
      pb.etc = pb.etc + (market_price - w.remain_value)
      pb.etc_revenue = pb.etc_revenue + market_price
      pb.etc_cost = pb.etc_cost + w.remain_value
      pb.save

      w.destroy
    end
    word = "Done! #{Time.now}"
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def place_order_bk
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting

    produce = ((number_with_precision(params[:produce_order], :precision=>1)).to_f * 1000000).to_i
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    old_onprocess = pb.onprocess_inventory_unit
    if pb.cash<((produce-old_onprocess) * game_setting.unit_cost)
      word = "เงินสดไม่เพียงพอ"
    elsif produce<0
      word = "ไม่สามารถระบุค่าติดลบได้"
    else
      factories = Factory.find(:all, :conditions=>["player_id=?", session[:player].id], :order=>"year")
      capacity = factories.size * game_setting.factory_capacity
      if produce>capacity
        word = 'เกินกำลังการผลิต,'
        produce = capacity
      end
      pb.onprocess_inventory_unit = produce
      pb.cash = pb.cash - ((produce-old_onprocess) * game_setting.unit_cost)
      pb.save
      word += "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def buy_put_option_a
    word = ''
    game = Game.find(session[:player].game_id)
    game_error = GameError.find(:first, :conditions=>["game_id=? AND year=?", game.id, game.current_year])

    put_unit = ((number_with_precision(params[:put_unit], :precision=>2)).to_f * 1000000).to_i
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    pb.cash = pb.cash + pb.put_option_cost
    pb.put_option_unit = 0
    pb.put_option_remain_unit = 0
    pb.put_option_cost = 0
    pb.save
    if pb.cash<(game_error.put_price_a * put_unit)
      word = "เงินสดไม่เพียงพอ"
    elsif put_unit<0
      word = "ระบุค่าิดลบไม่ได้"
    else
      pb.put_option_unit = put_unit
      pb.put_option_remain_unit = put_unit
      pb.put_option_cost = (game_error.put_price_a * put_unit)
      pb.cash = pb.cash - (game_error.put_price_a * put_unit)
      pb.save
      word += "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game_a", :word=>word
  end

  def place_order
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting

    produce = ((number_with_precision(params[:produce_order], :precision=>2)).to_f * 1000000).to_i
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    old_onprocess = pb.onprocess_inventory_unit
    if pb.rawmat_unit<produce
      word = "วัตถุดิบไม่เพียงพอ"
    elsif produce<0
      word = "ไม่สามารถระบุค่าติดลบได้"
    else
      factories = Factory.find(:all, :conditions=>["player_id=?", session[:player].id], :order=>"year")
      capacity = factories.size * game_setting.factory_capacity
      if produce>capacity
        word = 'เกินกำลังการผลิต,'
        produce = capacity
      end
      pb.onprocess_inventory_unit = produce
#      pb.rawmat_unit = pb.rawmat_unit - (produce-old_onprocess)
#      pb.rawmat_cost = pb.rawmat_unitcost * pb.rawmat_unit
      pb.save
      word += "Done! #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def marketing_upgrade
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    player = Player.find(session[:player].id)
    required_cash = 9999999999
    if player.level==0
      required_cash = game_setting.level1_required_marketing
    elsif player.level==1
      required_cash = game_setting.level2_required_marketing
    elsif player.level==2
      required_cash = game_setting.level3_required_marketing
    elsif player.level==3
      required_cash = game_setting.level4_required_marketing
    else
    end

    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    if pb.cash<required_cash
      word = 'เงินสดไม่เพียงพอ'
    else
      if player.level<=3
        player.level = player.level + 1
        player.save

        pb.cash = pb.cash - required_cash
        pb.marketing = required_cash
        pb.save
        word = "Done! #{Time.now}"
      else
        word = "Can not upgrade!"
      end
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def marketing_downgrade
    word = ''
    game = Game.find(session[:player].game_id)
    player = Player.find(session[:player].id)
    if player.level!=0
      player.level = player.level-1
      player.save
    end

    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    pb.cash = pb.cash + pb.marketing
    pb.marketing = 0
    pb.save
    word = "Done! #{Time.now}"
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def make_debt
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])

    begin
      loan_amount = 0
      if !params[:debt].empty?
        loan_amount = params[:debt].to_i * 1000000
      end
      old_debt = Debt.sum(:amount, :conditions=>["player_id=?", session[:player].id])
      debt = loan_amount + old_debt
      equity = pb.common_stock + pb.retain_earning
      
      last_year_debt = Debt.sum(:amount, :conditions=>["player_id=? AND year<?", session[:player].id, game.current_year])

      if ((debt/equity.to_f)>game_setting.de_limit)
        word = 'เกินอัตราส่วน D/E limit'
      elsif (debt/equity.to_f)<0 && (debt - last_year_debt)>40000000
        word = 'กรณีที่ท่านมี D/E ติดลบ ท่านสามารถกู้เพิ่มเติมได้เพียง 40 ล้านเท่านั้น'
      elsif loan_amount<=0
        word = 'ไม่สามารถใส่ 0 หรือค่าติดลบ'
      else
        max_code = 0
        last_d = Debt.find(:first, :conditions=>["player_id=?", session[:player].id], :order=>"id desc")
        if last_d
          max_code = last_d.code
        end
        d = Debt.new
        d.player_id = session[:player].id
        d.code = max_code + 1
        d.gencode = random_string(10)
        d.year = game.current_year
        d.amount = loan_amount
        if debt<=game_setting.level1_debt_limit
          d.interest_rate = game_setting.level1_debt_rate
          d.interest = loan_amount * game_setting.level1_debt_rate
        elsif debt<=game_setting.level2_debt_limit
          d.interest_rate = game_setting.level2_debt_rate
          d.interest = loan_amount * game_setting.level2_debt_rate
        elsif debt<=game_setting.level3_debt_limit
          d.interest_rate = game_setting.level3_debt_rate
          d.interest = loan_amount * game_setting.level3_debt_rate
        else
          d.interest_rate = game_setting.level4_debt_rate
          d.interest = loan_amount * game_setting.level4_debt_rate
        end
        d.start_year = game.current_year
        d.end_year = game.current_year + game_setting.longterm_debt_life - 1
        d.save

        pb.cash = pb.cash + loan_amount
        pb.save
        word = "Done #{Time.now}"
      end
    rescue
      word = "Error #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def pay_debt
    word = ''
    game = Game.find(session[:player].game_id)
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    
    debt = Debt.find(:first, :conditions=>["gencode=?", params[:id]])
    if debt
      if debt.amount>pb.cash
        word = 'เงินสดไม่เพียงพอ'
      else
        pb.cash = pb.cash - debt.amount
        pb.save
        debt.destroy
        word = "Done #{Time.now}"
      end
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

  def issue_common_stock
    word = ''
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year])
    last_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", session[:player].id, game.current_year-1])
    begin
      if game.current_year<=1
        word = 'ไม่สามารถดำเนินการได้, คุณสามารถออกหุ้นเพิ่มทุนได้ในปีที่ 2 เป็นต้นไป'
      else
        issue = 0
        if !params[:common].empty?
          issue = params[:common].to_i * 1000000
        end
        if issue<0
          old_equity = pb.common_stock + pb.retain_earning
          equity = old_equity + (pb.equity_per_share * issue)
          debt = Debt.sum(:amount, :conditions=>["player_id=?", session[:player].id])
          if ((debt/equity.to_f)>game_setting.de_limit)
            word = 'ไม่สามารถดำเนินการได้, เกิน D/E Limit'
          elsif pb.common_stock_unit+issue<game_setting.min_common_stock_unit
            word = "ไม่สามารถดำเนินการได้, จำนวนหุ้นสามัญต่ำสุดคือ #{number_with_delimiter(game_setting.min_common_stock_unit)} หุ้น"
          elsif pb.cash<(pb.equity_per_share * issue * -1)
            word = 'เงินสดไม่เพียงพอ'
          else
            cs_price = pb.common_stock.to_f/pb.common_stock_unit
            re_price = pb.equity_per_share - cs_price
            pb.common_stock = (pb.common_stock + (cs_price * issue)).to_i
            pb.retain_earning = (pb.retain_earning + (re_price * issue)).to_i
            pb.common_stock_unit = pb.common_stock_unit + issue
            pb.cash = pb.cash + (pb.equity_per_share * issue)
            pb.save
            word = "Done #{Time.now}"
          end
        end
        if issue>0
          last_equity = last_pb.equity_per_share * last_pb.common_stock_unit
          old_equity = pb.equity_per_share * pb.common_stock_unit
          equity = old_equity + (pb.equity_per_share * issue)
          if ((equity/last_equity.to_f)>game_setting.ee_limit)
            word = 'ไม่สามารถดำเนินการได้, เกิน Et/Et-1 Limit'
          else
            pb.common_stock = pb.common_stock + (pb.equity_per_share * issue)
            pb.common_stock_unit = pb.common_stock_unit + issue
            pb.cash = pb.cash + (pb.equity_per_share * issue)
            pb.save
            word = "Done #{Time.now}"
          end
        end
      end
    rescue
      word = "Error #{Time.now}"
    end
    redirect_to :controller=>"user", :action=>"plan_game", :word=>word
  end

end
